<template>
    <div>
        <div class="button-box">
            <div class="button-item button-item-right-border">
                <el-button link @click="saveTableData">
                    <el-icon size="18" color="#409EFF">
                        <Document />
                    </el-icon>
                    <span style="font-size: 14px;">保存</span>
                </el-button>
            </div>
            <div v-if="tabInfo==='field'" class="button-box">
                <div class="button-item">
                    <el-button link @click="handleAddRow">
                        <el-icon size="18" color="#67C23A">
                            <CirclePlus />
                        </el-icon>
                        <span style="font-size: 14px;">添加字段</span>
                    </el-button>
                </div>
                <div class="button-item">
                    <el-button link @click="handleInsertRow">
                        <el-icon size="18" color="#409EFF">
                            <Back />
                        </el-icon>
                        <span style="font-size: 14px;">插入字段</span>
                    </el-button>
                </div>
                <div class="button-item button-item-right-border">
                    <el-button link @click="handleDeleteField">
                        <el-icon size="18" color="#c45656">
                            <Remove />
                        </el-icon>
                        <span style="font-size: 14px;">删除字段</span>
                    </el-button>
                </div>
                <div class="button-item">
                    <el-button link @click="handlePrimaryKey">
                        <el-icon size="18" color="#c45656">
                            <Key />
                        </el-icon>
                        <span style="font-size: 14px;">主键</span>
                    </el-button>
                </div>
                <div class="button-item">
                    <el-button link @click="handleOnTop">
                        <el-icon size="18" color="#c45656">
                            <Top />
                        </el-icon>
                        <span style="font-size: 14px;">上移</span>
                    </el-button>
                </div>
                <div class="button-item">
                    <el-button link @click="handleOnBottom">
                        <el-icon size="18" color="#c45656">
                            <Bottom />
                        </el-icon>
                        <span style="font-size: 14px;">下移</span>
                    </el-button>
                </div>
            </div>
            <div v-if="tabInfo==='index'" class="button-box">
                <div class="button-item">
                    <el-button link @click="handleAddIndexRow">
                        <el-icon size="18" color="#67C23A">
                            <CirclePlus />
                        </el-icon>
                        <span style="font-size: 14px;">添加索引</span>
                    </el-button>
                </div>
                <div class="button-item">
                    <el-button link @click="handleDeleteIndex">
                        <el-icon size="18" color="#c45656">
                            <Remove />
                        </el-icon>
                        <span style="font-size: 14px;">删除索引</span>
                    </el-button>
                </div>
            </div>
            <div v-if="tabInfo==='outside'" class="button-box">
                <div class="button-item">
                    <el-button link @click="handleAddOutsideRow">
                        <el-icon size="18" color="#67C23A">
                            <CirclePlus />
                        </el-icon>
                        <span style="font-size: 14px;">添加外键</span>
                    </el-button>
                </div>
                <div class="button-item">
                    <el-button link @click="handleDeleteOutside">
                        <el-icon size="18" color="#c45656">
                            <Remove />
                        </el-icon>
                        <span style="font-size: 14px;">删除外键</span>
                    </el-button>
                </div>
            </div>
            <div v-if="tabInfo==='check'" class="button-box">
                <div class="button-item">
                    <el-button link @click="handleAddCheckRow">
                        <el-icon size="18" color="#67C23A">
                            <CirclePlus />
                        </el-icon>
                        <span style="font-size: 14px;">添加检查</span>
                    </el-button>
                </div>
                <div class="button-item">
                    <el-button link @click="handleDeleteCheck">
                        <el-icon size="18" color="#c45656">
                            <Remove />
                        </el-icon>
                        <span style="font-size: 14px;">删除检查</span>
                    </el-button>
                </div>
            </div>
            <div v-if="tabInfo==='trigger'" class="button-box">
                <div class="button-item">
                    <el-button link @click="handleAddTriggerRow">
                        <el-icon size="18" color="#67C23A">
                            <CirclePlus />
                        </el-icon>
                        <span style="font-size: 14px;">添加触发器</span>
                    </el-button>
                </div>
                <div class="button-item">
                    <el-button link @click="handleInsertTriggerRow">
                        <el-icon size="18" color="#409EFF">
                            <Back />
                        </el-icon>
                        <span style="font-size: 14px;">插入触发器</span>
                    </el-button>
                </div>
                <div class="button-item button-item-right-border">
                    <el-button link @click="handleDeleteTrigger">
                        <el-icon size="18" color="#c45656">
                            <Remove />
                        </el-icon>
                        <span style="font-size: 14px;">删除触发器</span>
                    </el-button>
                </div>
                <div class="button-item">
                    <el-button link @click="handleTriggerOnTop">
                        <el-icon size="18" color="#c45656">
                            <Top />
                        </el-icon>
                        <span style="font-size: 14px;">上移</span>
                    </el-button>
                </div>
                <div class="button-item">
                    <el-button link @click="handleTriggerOnBottom">
                        <el-icon size="18" color="#c45656">
                            <Bottom />
                        </el-icon>
                        <span style="font-size: 14px;">下移</span>
                    </el-button>
                </div>
            </div>
        </div>
        <el-tabs type="border-card" v-model="tabInfo" @tab-change="getTabInfo">
            <el-tab-pane label="字段" name="field">
                <el-table :data="fieldData" size="small" border class="table-tab" @row-click="handleFieldClick">
                    <el-table-column prop="fieldName" width="300" fixed label="名">
                        <template #default="scope">
                            <input v-model="scope.row.fieldName" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="fieldType" width="120" label="类型">
                        <template #default="scope">
                            <el-select v-model="scope.row.fieldType" filterable remote reserve-keyword clearable
                                style="width: 100%">
                                <el-option v-for="item in fieldTypes" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="fieldLength" label="长度" width="100">
                        <template #default="scope">
                            <input v-model="scope.row.fieldLength"
                                @input="handleInputNumber(scope.row,'fieldLength',scope.row.fieldLength)" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="fieldDecimal" label="小数" width="100">
                        <template #default="scope">
                            <input v-model="scope.row.fieldDecimal"
                                @input="handleInputNumber(scope.row,'fieldDecimal',scope.row.fieldDecimal)" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="fieldNotNull" label="不是NULL" width="100">
                        <template #default="scope">
                            <el-checkbox :checked="scope.row.fieldNotNull ==='YES'?false:true" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="key" label="键" width="100">
                        <template #default="scope">
                            <div @click="operatePrimaryKey(scope.row)"
                                style="width: 100%;height:20px;line-height: 20px;">
                                <Icon icon="noto-v1:key" style="font-size: 16px;"
                                    v-if="getPrimaryKeyIndex(scope.row)>0" />
                                <span style="font-size: 16px;margin-left: 5px;"
                                    v-if="getPrimaryKeyIndex(scope.row)>0">{{ getPrimaryKeyIndex(scope.row) }}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="fieldComment" label="注释" min-width="300">
                        <template #default="scope">
                            <input v-model="scope.row.fieldComment" />
                        </template>
                    </el-table-column>
                </el-table>
                <div>
                    <div class="flex-div">
                        <div style="text-align: left;font-size:12px;width:120px;">默认:</div>
                        <div style="width: 200px;"><el-input v-model="fieldForm.fieldDefault" size="small"/></div>
                    </div>
                    <div class="flex-div" v-if="getColumnType(fieldForm.fieldType)==='number'">
                        <div style="text-align: left;width: 120px;"><el-checkbox v-model="fieldForm.fieldAutoIncrement" label="自动递增" size="small" /></div>
                    </div>
                    <div class="flex-div"  v-if="getColumnType(fieldForm.fieldType)==='number'">
                        <div style="text-align: left;width: 120px;"><el-checkbox v-model="fieldForm.fieldUnsigned" label="无符号" size="small" /></div>
                    </div>
                    <div class="flex-div"  v-if="getColumnType(fieldForm.fieldType)==='number'">
                        <div style="text-align: left;width: 120px;"><el-checkbox v-model="fieldForm.fieldZerofill" label="填充零" size="small" /></div>
                    </div>
                    <div class="flex-div" v-if="getColumnType(fieldForm.fieldType)==='text'">
                        <div style="text-align: left;font-size:12px;width:120px;">字符集:</div>
                        <div style="width: 200px;">
                            <el-select v-model="fieldForm.fieldCharactrSetName" filterable clearable @change="getCollationOptions"  size="small">
                                <el-option v-for="item in characterSetOptions" :key="item.CHARACTER_SET_NAME"  :label="item.CHARACTER_SET_NAME" :value="item.CHARACTER_SET_NAME" />
                            </el-select>
                        </div>
                    </div>
                    <div class="flex-div" v-if="getColumnType(fieldForm.fieldType)==='text'">
                        <div style="text-align: left;font-size:12px;width:120px;">排序规则:</div>
                        <div style="width: 200px;">
                            <el-select v-model="fieldForm.fieldCollate" filterable clearable  size="small">
                                <el-option v-for="item in collateOptionsMap['field_'+fieldForm.id]" :key="item.COLLATION_NAME" :label="item.COLLATION_NAME" :value="item.COLLATION_NAME" />
                            </el-select>
                        </div>
                    </div>
                    <div class="flex-div" v-if="getColumnType(fieldForm.fieldType)==='date'">
                        <div style="text-align: left;font-size:12px;width: 120px;"><el-checkbox v-model="fieldForm.fieldTimestamp" label="根据当前时间戳更新" size="small" /></div>
                    </div>
                </div>
            </el-tab-pane>
            <el-tab-pane label="索引" name="index">
                <el-table :data="keyData" size="small" class="table-tab-all" border @row-click="handleIndexClick">
                    <el-table-column prop="keyName" label="名" fixed width="200">
                        <template #default="scope">
                            <input v-model="scope.row.keyName" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="keyFields" label="字段" min-width="300">
                        <template #default="scope">
                            <div class="key-field" @click="openKeyFields(scope.row)">
                                <el-scrollbar>
                                    <span v-for="(column,index) in getShowColumns(scope.row.keyFields)"
                                        style="justify-content: flex-start;">
                                        <span v-if="index>0">,</span>
                                        <span>{{column}}</span>
                                    </span>
                                </el-scrollbar>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="keyType" label="索引类型" width="120">
                        <template #default="scope">
                            <el-select v-model="scope.row.keyType" filterable remote reserve-keyword clearable
                                style="width: 100%">
                                <el-option v-for="item in keyTypes" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="keyMethod" label="索引方法" width="120">
                        <template #default="scope">
                            <el-select v-model="scope.row.keyMethod" filterable remote reserve-keyword clearable
                                style="width: 100%">
                                <el-option v-for="item in keyMethods" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="keyComment" label="注释" width="300">
                        <template #default="scope">
                            <input v-model="scope.row.keyComment" />
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="外键" name="outside">
                <el-table :data="outsideData" size="small" class="table-tab-all" border @row-click="handleOutsideClick">
                    <el-table-column prop="outsideName" label="名" min-width="100">
                        <template #default="scope">
                            <input v-model="scope.row.outsideName" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="outsideFields" label="字段" width="200">
                        <template #default="scope">
                            <el-select v-model="scope.row.outsideFields" filterable multiple clearable collapse-tags collapse-tags-tooltip >
                                <el-option v-for="item in fieldData" :key="item.fieldName" :label="item.fieldName"
                                    :value="item.fieldName" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="outsideModel" label="被引用模式" min-width="150">
                        <template #default="scope">
                            <el-select v-model="scope.row.outsideModel" filterable clearable
                                @change="getTableList(scope.row)">
                                <el-option v-for="item in getDataBaseList()" :key="item.schema_name"
                                    :label="item.schema_name" :value="item.schema_name" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="outsideParentTable" label="被引用表(父)" min-width="150">
                        <template #default="scope">
                            <el-select v-model="scope.row.outsideParentTable" filterable clearable
                                @change="getTableFields(scope.row)">
                                <el-option v-for="item in outsideParentTables[scope.row.id]" :key="item.table_name"
                                    :label="item.table_name" :value="item.table_name" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="outsideParentTableFiled" label="被引用字段" width="200">
                        <template #default="scope">
                            <el-select v-model="scope.row.outsideParentTableFiled" filterable multiple clearable collapse-tags collapse-tags-tooltip >
                                <el-option v-for="item in outsideParentTableFields[scope.row.id]"
                                    :key="item.COLUMN_NAME" :label="item.COLUMN_NAME" :value="item.COLUMN_NAME" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="deleteEvent" label="删除时" width="150">
                        <template #default="scope">
                            <el-select v-model="scope.row.deleteEvent" filterable remote reserve-keyword clearable>
                                <el-option v-for="item in outsideEvents" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="updateEvent" label="更新时" width="150">
                        <template #default="scope">
                            <el-select v-model="scope.row.updateEvent" filterable remote reserve-keyword clearable>
                                <el-option v-for="item in outsideEvents" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="检查" name="check">
                <el-table :data="checkData" size="small" class="table-tab-all" border @row-click="handleCheckClick">
                    <el-table-column prop="checkName" label="名">
                        <template #default="scope">
                            <input v-model="scope.row.checkName" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="checkScript" label="检查">
                        <template #default="scope">
                            <input v-model="scope.row.checkScript" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="checkNotRequired" label="不强制实施">
                        <template #default="scope">
                            <input v-model="scope.row.checkNotRequired" />
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="触发器" name="trigger">
                <el-table :data="triggerData" size="small" class="table-tab-all" border @row-click="handleTriggerClick">
                    <el-table-column prop="triggerName" label="名">
                        <template #default="scope">
                            <input v-model="scope.row.triggerName" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="triggerEvent" label="触发">
                        <template #default="scope">
                            <el-select v-model="scope.row.triggerEvent" filterable clearable>
                                <el-option v-for="item in triggerEvents" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="triggerInsert" label="插入">
                        <template #default="scope">
                            <el-checkbox  v-model="scope.row.triggerInsert"  @change="triggerCheckboxChange(scope.row,'triggerInsert')" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="triggerUpdate" label="更新">
                        <template #default="scope">
                            <el-checkbox  v-model="scope.row.triggerUpdate"  @change="triggerCheckboxChange(scope.row,'triggerUpdate')"/>
                        </template>
                    </el-table-column>
                    <el-table-column prop="triggerDelete" label="删除">
                        <template #default="scope">
                            <el-checkbox  v-model="scope.row.triggerDelete"  @change="triggerCheckboxChange(scope.row,'triggerDelete')"/>
                        </template>
                    </el-table-column>
                </el-table>

            </el-tab-pane>
            <el-tab-pane label="选项" name="option">
                <div class="table-tab-all" style="width: 45vw;">
                    <el-scrollbar>
                        <el-form :model="metaData" label-width="120" size="small" label-position="left">
                            <el-form-item label="引擎">
                                <el-select v-model="metaData.metaEngine" filterable clearable>
                                    <el-option v-for="item in enginesOptions" :key="item.engine" :label="item.engine"
                                        :value="item.engine" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="字符集">
                                <el-select v-model="metaData.metaCharset" filterable clearable
                                    @change="getCollationNameOptions">
                                    <el-option v-for="item in characterSetOptions" :key="item.CHARACTER_SET_NAME"
                                        :label="item.CHARACTER_SET_NAME" :value="item.CHARACTER_SET_NAME" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="排序规则">
                                <el-select v-model="metaData.metaCollate" filterable clearable>
                                    <el-option v-for="item in collateOptions" :key="item.COLLATION_NAME"
                                        :label="item.COLLATION_NAME" :value="item.COLLATION_NAME" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="行格式">
                                <el-select v-model="metaData.metaRowFormat" filterable clearable>
                                    <el-option v-for="item in rowFormatOptions" :key="item.label" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="自动递增">
                                <el-input v-model="metaData.metaAutoIncrement" />
                            </el-form-item>
                        </el-form>
                    </el-scrollbar>
                </div>
            </el-tab-pane>
            <el-tab-pane label="注释" name="comment">
                <el-input v-model="metaData.metaComment" type="textarea" :rows="20"/>
            </el-tab-pane>
            <el-tab-pane label="SQL预览" name="preview">
                <div class="preview-box">
                    {{sqlPreview}}
                </div>
            </el-tab-pane>
        </el-tabs>
    </div>


    <el-dialog v-model="designDialogOpen" v-if="designDialogOpen" width="500"  :show-close="false">
        <el-table :data="designData" border height="350" @row-click="tableClickRow">
            <el-table-column type="index" width="50" fixed>
                <template #default="scope">
                    <div style="width: 100%;display: flex;justify-content: flex-start;">
                        <div v-if="selectRowIndex === (scope.$index + 1)"><el-icon size="18">
                                <CaretRight />
                            </el-icon></div>
                        <div>{{ initDialogIndex(scope.$index) }}</div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="column" label="名">
                <template #default="scope">
                    <el-select v-model="scope.row.column" style="width: 100%">
                        <el-option v-for="item in fieldData" :key="item.fieldName" :label="item.fieldName"
                            :value="item.fieldName" />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序" width="180">
                <template #default="scope">
                    <el-select v-model="scope.row.sort" style="width: 100%">
                        <el-option v-for="item in sortOptions" :key="item.label" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </template>
            </el-table-column>
        </el-table>
        <template #footer>
            <div class="dialog-footer footer-button">
                <div class="footer-button-item">
                    <el-button text small icon="Top"     @click="dialogOnUpIndexRow"></el-button>
                    <el-button text small icon="Bottom"  @click="dialogOnBottomIndexRow"></el-button>
                    <el-button text small icon="Plus"    @click="dialogAddIndexRow"></el-button>
                    <el-button text small icon="Minus"   @click="dialogRemoveIndexRow" ></el-button>
                </div>
                <div class="footer-button-item">
                    <el-button small @click=" designDialogOpen = false">取消</el-button>
                    <el-button small type="primary" @click="confirmUpdate">确认</el-button>
                </div>
            </div>
        </template>
    </el-dialog>
</template>


<script setup name="tableDesignView">
    import {decomposeCreateTableScript} from "@/utils/tableUtils";
    import {queryTableList, queryTableFields, queryTableEngines} from '@/utils/connectManager';
    import {getPrimaryKey,handleInsert} from "@/utils/arrayUtils";

    const {proxy} = getCurrentInstance();
    const connection = ref(null);
    const sqlPreview = ref(null)
    const tableData = reactive({
        fieldData: [],//字段信息
        primaryKey: [],//主键信息
        keyData: [],//索引信息
        outsideData: [],//外键信息
        triggerData: [],//触发器信息
        checkData: [],//检查数据
        metaData: {},//表元数据
    })
    const {fieldData, primaryKey, keyData, outsideData, triggerData, checkData, metaData} = toRefs(tableData)
    const indexData = reactive({
        fieldIndex: 0,//字段信息
        keyIndex: [],//索引信息
        outsideIndex: [],//外键信息
        triggerIndex: [],//触发器信息
        checkIndex: [],//检查数据
    })
    const {fieldIndex, keyIndex, outsideIndex, triggerIndex, checkIndex} = toRefs(indexData)
    const designDialog=reactive({
        designDialogOpen:false,
        designData:[],
        selectRowIndex:null,
        selectRow:null,
        designDataIndex:null
    });
    const {designDialogOpen, designData,selectRowIndex,selectRow,designDataIndex} = toRefs(designDialog)
    const originalTable=ref({});
    const tabInfo = ref('field')
    const fieldTypes = ref([
        {label: 'tinyint', value: 'tinyint', type: 'number'},
        {label: 'smallint', value: 'smallint', type: 'number'},
        {label: 'mediumint', value: 'mediumint', type: 'number'},
        {label: 'int', value: 'int', type: 'number'},
        {label: 'bigint', value: 'bigint', type: 'number'},
        {label: 'float', value: 'float', type: 'number'},
        {label: 'double', value: 'double', type: 'number'},
        {label: 'decimal', value: 'decimal', type: 'number'},
        {label: 'date', value: 'date', type: 'date'},
        {label: 'time', value: 'time', type: 'date'},
        {label: 'year', value: 'year', type: 'date'},
        {label: 'datetime', value: 'datetime', type: 'date'},
        {label: 'timestamp', value: 'timestamp', type: 'date'},
        {label: 'char', value: 'char', type: 'date'},
        {label: 'varchar', value: 'varchar', type: 'text'},
        {label: 'tinyblob', value: 'tinyblob', type: 'text'},
        {label: 'tinytext', value: 'tinytext', type: 'text'},
        {label: 'blob', value: 'blob', type: 'text'},
        {label: 'text', value: 'text', type: 'text'},
        {label: 'mediumblob', value: 'mediumblob', type: 'text'},
        {label: 'mediumtext', value: 'mediumtext', type: 'text'},
        {label: 'longblob', value: 'longblob', type: 'text'},
        {label: 'longtext', value: 'longtext', type: 'text'},
    ])
    const keyTypes = ref([
        {label: 'FULLTEXT', value: 'FULLTEXT'},
        {label: 'NORMAL', value: 'NORMAL'},
        {label: 'SPATIAL', value: 'SPATIAL'},
        {label: 'UNIQUE', value: 'UNIQUE'},
    ])
    const keyMethods = ref([
        {label: 'BTREE', value: 'BTREE'},
        {label: 'HASH', value: 'HASH'},
    ])
    const outsideParentTables = ref({})
    const outsideParentTableFields = ref({})
    const outsideEvents = ref([
        {label: 'CASCADE', value: 'CASCADE'},
        {label: 'NO ACTION', value: 'NO ACTION'},
        {label: 'RESTRICT', value: 'RESTRICT'},
        {label: 'SET NULL', value: 'SET NULL'},
    ])
    const triggerEvents = ref([
        {label: 'BEFORE', value: 'BEFORE'},
        {label: 'AFTER', value: 'AFTER'},
    ])
    const sortOptions = ref([
        {label: 'ASC', value: 'ASC'},
        {label: 'DESC', value: 'DESC'},
    ])
    const enginesOptions = ref([])
    const characterSetOptions = ref([])
    const collateOptions = ref([])
    const collateOptionsMap=ref({})
    const rowFormatOptions = ref([
        {label: 'COMPACT', value: 'COMPACT'},
        {label: 'COMPRESSED', value: 'COMPRESSED'},
        {label: 'DEFAULT', value: 'DEFAULT'},
        {label: 'DYNAMIC', value: 'DYNAMIC'},
        {label: 'FIXED', value: 'FIXED'},
        {label: 'REDUNDANT', value: 'REDUNDANT'},
    ])

    const fieldForm=ref({})

    // TODO SHOW INDEX FROM 表名  查索引
    // TODO SHOW COLUMNS FROM 表名 查列信息
    function initTableInfo() {
        connection.value = proxy.$appStore.connectList.find(item => item.id === (proxy.$route.query.connectId * 1));
        connection.value.databaseName=proxy.$route.query?.databaseName
        proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.charSetNameOptions,connection.value,{}).then(res=>{
            characterSetOptions.value=[]
            if(res.code===200){
                characterSetOptions.value=res.data.dataList
            }
        })
        fieldIndex.value=0
        if(proxy.$route.query?.tableName){
            let params={}
            params.databaseKey=proxy.$route.query.databaseName
            params.tableKey=proxy.$route.query.tableName
            proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.selectTableFields,connection.value,params).then(res=>{
                fieldData.value=[]
                if(res.code===200){
                    res.data.dataList.forEach(fieldRow=>{
                        fieldData.value.push(getFieldRow(fieldRow))
                    })
                }
            })
            proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.getTableTriggersList,connection.value,params).then(res=>{
                triggerData.value=[]
                if(res.code===200){
                    res.data.dataList.forEach(triggerInfo=>{
                        triggerData.value.push(getTriggerRow(triggerInfo))
                    })
                }
                if(triggerData.value.length<1){
                    triggerData.value.push(getTriggerRow())
                }
            })
            
            params.runScript="SHOW CREATE TABLE "+params.tableKey
            proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.runConsole, connection.value, params).then(res => {
                if (res.code === 200) {
                    let tableInfo = decomposeCreateTableScript(res.data.dataList[0]['Create Table'], proxy.$route.query.databaseName, proxy.$route.query.tableName)
                    originalTable.value=JSON.parse(JSON.stringify(tableInfo))
                    primaryKey.value = tableInfo.primaryList
                    keyData.value = tableInfo.indexList
                    if(keyData.value.length<1){
                        keyData.value.push(getIndexRow())
                    }
                    outsideData.value = tableInfo.outsideList
                    if(outsideData.value.length<1){
                        outsideData.value.push(getOutsideRow())
                    }
                    triggerData.value = []
                    if(triggerData.value.length<1){
                        triggerData.value.push(getTriggerRow())
                    }
                    checkData.value = tableInfo.checkList
                    if(checkData.value.length<1){
                        checkData.value.push(getCheckRow())
                    }
                    metaData.value.metaCharset = tableInfo.metaData.metaCharset
                    getCollationNameOptions()
                    metaData.value=tableInfo.metaData
                }
            })
        }else {
            handleInsertRow()
            handleAddIndexRow()
            handleAddCheckRow()
            handleAddTriggerRow()
            handleAddOutsideRow()
        }
    }


    function getCollationNameOptions(){
        metaData.value.metaCollate=null
        collateOptions.value=[]
        proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.collationNameOptions,connection.value,{charSetName:metaData.value.metaCharset}).then(res=>{
            if(res.code===200){
                collateOptions.value=res.data.dataList
            }
        })
    }

   function getCollationOptions(){
    proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.collationNameOptions,connection.value,{charSetName:fieldForm.value.fieldCharactrSetName}).then(res=>{
            if(res.code===200){
                collateOptionsMap.value['field_'+fieldForm.value.id]=res.data.dataList
            }
        })
    }


    function getDataBaseList(){
        let databaseList=proxy.$appStore.usedConnect[connection.value.id]
        if(databaseList&&databaseList.usedDatabase){
            return  databaseList.usedDatabase
        }
        return []
    }

    function saveTableData() {
        console.log('保存')
    }

    const handleEvent = async (event) => {
        if (event.keyCode === 83) {
            if (event.ctrlKey && event.code === 'KeyS') {
                event.preventDefault()
                event.returnValue = false;
                saveTableData()
            }
        }
    }

    onMounted(() => {
        window.addEventListener('keydown', handleEvent)
    });

    onUnmounted(() => {
        window.removeEventListener('keydown', handleEvent)
    });

    function handleInputNumber(row, key, number) {
        if (isNaN((number * 1))) {
            row[key] = null
        } else {
            row[key] = (number * 1)
        }
    }

    function operatePrimaryKey(item) {
        if (!item.fieldName || item.fieldName.trim().length < 1) {
            proxy.$modal.msgWarning("请填写字段名")
            return
        }
        let localPrimaryKey = primaryKey.value.find(keyName => keyName === item.fieldName)
        if (!localPrimaryKey) {
            primaryKey.value.push(item.fieldName)
        } else {
            let index = primaryKey.value.indexOf(localPrimaryKey)
            if (index != -1) {
                primaryKey.value.splice(index, 1)
            }
        }
    }

    function getPrimaryKeyIndex(item) {
        let localPrimaryKey = primaryKey.value.find(keyName => keyName === item.fieldName)
        return primaryKey.value.indexOf(localPrimaryKey) + 1
    }

    function handleFieldClick(row) {
        fieldIndex.value = fieldData.value.indexOf(fieldData.value.find(item => item.id === row.id))
        fieldForm.value=fieldData.value[fieldIndex.value]
        getCollationOptions()
    }

    function handleDeleteField() {
        fieldData.value.splice(fieldIndex.value, 1)
        let maxIndex = fieldData.value.length - 1
        if (fieldIndex.value > maxIndex) {
            fieldIndex.value = maxIndex
        }
        if (maxIndex == -1) {
            handleAddRow()
            fieldIndex.value = 0
        }
        fieldForm.value=fieldData.value[fieldIndex]
    }

    function getFieldRow(fieldRow) {
        let row = {}
        if (fieldRow) {
            row.id = fieldRow.ORDINAL_POSITION
            row.fieldName = fieldRow.COLUMN_NAME
            row.fieldType = fieldRow.DATA_TYPE
            row.fieldLength = fieldRow.CHARACTER_MAXIMUM_LENGTH ? fieldRow.CHARACTER_MAXIMUM_LENGTH : fieldRow.NUMERIC_PRECISION
            row.fieldDecimal = fieldRow.NUMERIC_SCALE
            if (!fieldRow.COLUMN_TYPE.includes("(")) {
                row.fieldLength = null
                row.fieldDecimal = null
            }
            row.fieldNotNull = fieldRow.IS_NULLABLE
            row.fieldComment = fieldRow.COLUMN_COMMENT
            row.fieldDefault = fieldRow.COLUMN_DEFAULT
            row.fieldCharactrSetName = fieldRow.CHARACTER_SET_NAME
            row.fieldCollate = fieldRow.COLLATION_NAME
            row.fieldAutoIncrement = fieldRow.EXTRA === 'auto_increment'
            row.fieldUnsigned = fieldRow.COLUMN_TYPE.includes('unsigned')
            row.fieldZerofill = fieldRow.COLUMN_TYPE.includes('zerofill')
            if (fieldRow.COLUMN_KEY && fieldRow.COLUMN_KEY === 'PRI') {
                primaryKey.value.push(fieldRow.COLUMN_NAME)
            }
            row.fieldTimestamp = false
        } else {
            row.id = getPrimaryKey()
            row.fieldName = null
            row.fieldType = null
            row.fieldLength = null
            row.fieldDecimal = null
            row.fieldNotNull = null
            row.fieldComment = null
            row.fieldDefault = null
            row.fieldCharactrSetName = null
            row.fieldCollate = null
            row.fieldAutoIncrement = false
            row.fieldUnsigned = false
            row.fieldZerofill = false
            row.fieldTimestamp = false
        }
        return row
    }

    function getIndexRow() {
        let row = {}
        row.id = getPrimaryKey()
        row.keyName = null
        row.keyFields = []
        row.keyType = null
        row.keyMethod = null
        row.keyComment = null
        return row
    }

    function getOutsideRow() {
        let row = {}
        row.id = getPrimaryKey()
        row.outsideName = null
        row.outsideFields = []
        row.outsideModel = null
        row.outsideParentTable = null
        row.outsideParentTableFiled = null
        row.deleteEvent = null
        row.updateEvent = null
        return row
    }

    function handleAddRow() {
        fieldData.value.push(getFieldRow())
    }

    function handleInsertRow() {
        handleInsert(fieldData.value,fieldIndex.value,getFieldRow())
    }

    function handlePrimaryKey() {
        let row = fieldData.value[fieldIndex.value]
        operatePrimaryKey(row)
    }

    function handleOnTop() {
        if (fieldIndex.value > 0) {
            let localFieldData = fieldData.value;
            localFieldData[fieldIndex.value] = localFieldData.splice(fieldIndex.value - 1, 1, localFieldData[fieldIndex.value])[0];
            fieldData.value = [...localFieldData];
            fieldIndex.value = fieldIndex.value - 1
        }

    }

    function handleOnBottom() {
        if (fieldIndex.value < (fieldData.value.length - 1)) {
            let localFieldData = fieldData.value;
            localFieldData[fieldIndex.value] = localFieldData.splice(fieldIndex.value + 1, 1, localFieldData[fieldIndex.value])[0];
            fieldData.value = [...localFieldData];
            fieldIndex.value = fieldIndex.value + 1
        }
    }


    function handleAddIndexRow() {
        keyData.value.push(getIndexRow())
    }

    function handleDeleteIndex() {
        keyData.value.splice(keyIndex.value, 1)
        let maxIndex = keyData.value.length - 1
        if (keyIndex.value > maxIndex) {
            keyIndex.value = maxIndex
        }
        if (maxIndex == -1) {
            handleAddIndexRow()
            keyIndex.value = 0
        }
    }

    function handleIndexClick(row) {
        keyIndex.value = keyData.value.indexOf(keyData.value.find(item => item.id === row.id))
    }

    function handleOutsideClick(row) {
        outsideIndex.value = outsideData.value.indexOf(outsideData.value.find(item => item.id === row.id))
    }

    function handleAddOutsideRow() {
        outsideData.value.push(getOutsideRow())
    }

    function handleDeleteOutside() {
        outsideData.value.splice(outsideIndex.value, 1)
        let maxIndex = outsideData.value.length - 1
        if (outsideIndex.value > maxIndex) {
            outsideIndex.value = maxIndex
        }
        if (maxIndex == -1) {
            handleAddOutsideRow()
            outsideIndex.value = 0
        }
    }

    function getTableList(row) {
        let options = []
        queryTableList(proxy, connection.value, row.outsideModel, options)
        outsideParentTables.value[row.id] = options
        row.outsideParentTable = null
        row.outsideParentTableFiled = null
    }

    function getTableFields(row) {
        queryTableFields(proxy, connection.value, row.outsideModel, row.outsideParentTable).then(res=>{
            console.log('res==',res)
          outsideParentTableFields.value[row.id]=res.data.dataList
        })
        row.outsideParentTableFiled = null
    }

    function handleCheckClick(row) {
        checkIndex.value = checkData.value.indexOf(checkData.value.find(item => item.id === row.id))
    }

    function getCheckRow() {
        let row = {}
        row.id = getPrimaryKey()
        row.checkName = null
        row.checkScript = null
        row.checkNotRequired = null
        return row
    }

    function handleAddCheckRow() {
        checkData.value.push(getCheckRow())
    }

    function handleDeleteCheck() {
        checkData.value.splice(checkIndex.value, 1)
        let maxIndex = checkData.value.length - 1
        if (checkIndex.value > maxIndex) {
            checkIndex.value = maxIndex
        }
        if (maxIndex == -1) {
            handleAddCheckRow()
            checkIndex.value = 0
        }
    }

    function handleTriggerClick(row) {
        triggerIndex.value = triggerData.value.indexOf(triggerData.value.find(item => item.id === row.id))
    }

    function getTriggerRow(triggerRow) {
        let row = {}
        row.id = getPrimaryKey()
        row.triggerName = null
        row.triggerEvent = null
        row.triggerInsert = false
        row.triggerUpdate = false
        row.triggerDelete = false
        if(triggerRow){
            row.triggerName = triggerRow.TRIGGER_NAME
            row.triggerEvent = triggerRow.ACTION_TIMING
            row.triggerInsert = triggerRow.EVENT_MANIPULATION==='INSERT'
            row.triggerUpdate = triggerRow.EVENT_MANIPULATION==='UPDATE'
            row.triggerDelete = triggerRow.EVENT_MANIPULATION==='DELETE'
        }
        return row
    }

    function handleAddTriggerRow() {
        triggerData.value.push(getTriggerRow())
    }

    function handleInsertTriggerRow() {
        triggerData.value.splice(triggerIndex.value, 0, getTriggerRow())
    }

    function handleDeleteTrigger() {
        triggerData.value.splice(triggerIndex.value, 1)
        let maxIndex = triggerData.value.length - 1
        if (triggerIndex.value > maxIndex) {
            triggerIndex.value = maxIndex
        }
        if (maxIndex == -1) {
            handleAddTriggerRow()
            triggerIndex.value = 0
        }
    }

    function handleTriggerOnTop() {
        if (triggerIndex.value > 0) {
            let localTriggerData = fieldData.value;
            localTriggerData[triggerIndex.value] = localTriggerData.splice(triggerIndex.value - 1, 1, localTriggerData[triggerIndex.value])[0];
            triggerData.value = [...localTriggerData];
            triggerIndex.value = triggerIndex.value - 1
        }

    }

    function handleTriggerOnBottom() {
        if (triggerIndex.value < (triggerData.value.length - 1)) {
            let localTriggerData = triggerData.value;
            localTriggerData[triggerIndex.value] = localTriggerData.splice(triggerIndex.value + 1, 1, localTriggerData[triggerIndex.value])[0];
            triggerData.value = [...localTriggerData];
            triggerIndex.value = triggerIndex.value + 1
        }
    }


    function selectEngines() {
        queryTableEngines(proxy, connection.value, enginesOptions.value)
    }

    function getTabInfo() {
        if (tabInfo.value === 'preview') {
            sqlPreview.value = null
            sqlPreview.value = '123456'
        }
    }

    function getShowColumns(columns){
        let content=[]
        columns.forEach(row=>{
            content.push(`\`${row.column}\` ${row.sort}`)
        })
        return content
    }

    function openKeyFields(item){
        designDialogOpen.value=true
        designDataIndex.value=keyData.value.indexOf(item)
        designData.value=JSON.parse(JSON.stringify(item.keyFields))
        if(designData.value&&designData.value.length>0){
            selectRowIndex.value=1
            selectRow.value=designData.value[0]
        }
    }

   function initDialogIndex(index){
        let rowIndex = index + 1
        return rowIndex;
    }

    function tableClickRow(row,column,event){
        selectRowIndex.value=(designData.value.indexOf(row)+1)
        selectRow.value=row
    }

    function dialogAddIndexRow(){
        let row={}
        row.column=null
        row.sort="ASC"
        designData.value.push(row)
    }

    function dialogRemoveIndexRow(){
        let index=designData.value.length-1
        designData.value.splice(index, 1)
        let maxIndex = designData.value.length - 1
        if (index > maxIndex) {
            index = maxIndex
            selectRowIndex.value = index+1
        }
        if (maxIndex == -1) {
            handleAddTriggerRow()
            selectRowIndex.value = 1
        }
    }

    function dialogOnUpIndexRow(){
        let index=selectRowIndex.value-1
        if (index >0) {
            let localDesignData = designData.value;
            localDesignData[index] = localDesignData.splice(index-1, 1, localDesignData[index])[0];
            designData.value = [...localDesignData];
            selectRowIndex.value = index
        }
    }

    function dialogOnBottomIndexRow(){
        let index=selectRowIndex.value-1
        if (index<(designData.value.length-1)) {
            let localDesignData = designData.value;
            localDesignData[index] = localDesignData.splice(index+1, 1, localDesignData[index])[0];
            designData.value = [...localDesignData];
            selectRowIndex.value = index+2
        }
    }

    function confirmUpdate(){
        keyData.value[designDataIndex.value].keyFields=designData.value
        designDialogOpen.value=false
        // console.log('tablediff',originalTable.value,keyData.value)
    }

    function triggerCheckboxChange(item,keyName){
       Object.keys(item).forEach(key=>{
        if(key.includes('triggerInsert')||key.includes('triggerUpdate')||key.includes('triggerDelete')){
            if(key!==keyName){
                item[key]=false
            }
        }
       })
    }

    function getColumnType(columnDataType){
        let columnType=''
        let labelOption=fieldTypes.value.find(row=>row.label===columnDataType);
        if(labelOption){
            columnType=labelOption.type
        }
        return columnType
    }


    initTableInfo()
    selectEngines()
    watch(fieldData,(newVal,oldVal)=>{
        fieldForm.value=fieldData.value[fieldIndex.value]
    })   
</script>

<style scoped lang="scss" >
    input {
        border: none;
        background: none;
        outline: none;
    }

    input:focus {
        border: none;
        background: none;
        outline: none;
    }

    :deep(.el-table) {
        --el-table-row-hover-bg-color: transparent;
        --el-table-header-bg-color: transparent;
        --el-table-header-text-color: #303133;
    }

    :deep(.el-table thead th) {
        font-weight: normal;
    }

    .button-box {
        width: 100%;
        height: 32px;
        line-height: 32px;
        background: #F5F7FA;
        display: flex;
        justify-content: flex-start;
    }

    .button-item {
        padding: 0 5px;
    }

    .button-item-right-border {
        border-right: 1px solid #E4E7ED;
    }

    .table-tab {
        width: 100%;
        height: calc(100vh - 350px);
        font-size: 12px;
    }

    .table-tab-all {
        width: 100%;
        height: calc(100vh - 220px);
        font-size: 12px;
    }

    .preview-box {
        width: 100%;
        height: calc(100vh - 220px);
        border-radius: 5px;
        border: 1px solid #D4D7DE;
        font-size: 12px;
        text-align: left;
        padding: 10px 0px 0px 10px;
    }

    .key-field{
        display: flex;
        user-select: text;
        cursor: pointer;
        width: 100%;
        height: 30px;
    }
    .key-field:active{
        background-color: #d9ecff;
    }
    .footer-button{
        display: flex;
        &-item{
            width: 50%;
            justify-content: space-between;
        }
    }
    .flex-div{
        display: flex;
        justify-content: flex-start;
        margin-top: 3px;
        margin-left: 5px;
    }





</style>
